<!--
 *Author：jxx
 *Contact：283591387@qq.com
 *业务请在@/extension/wms/realt/realtimeinventory.jsx或realtimeinventory.vue文件编写
 *新版本支持vue或【表.jsx]文件编写业务,文档见:https://v3.volcore.xyz/docs/view-grid、https://v3.volcore.xyz/docs/web
 -->
<template>
    <view-grid ref="grid"
               :columns="enhancedColumns"
               :detail="detail"
               :details="details"
               :editFormFields="editFormFields"
               :editFormOptions="editFormOptions"
               :searchFormFields="searchFormFields"
               :searchFormOptions="searchFormOptions"
               :table="table"
               :extend="extend"
               :onInit="onInit"
               :onInited="onInited"
               :searchBefore="searchBefore"
               :searchAfter="searchAfter"
               :addBefore="addBefore"
               :updateBefore="updateBefore"
               :rowClick="rowClick"
               :modelOpenBefore="modelOpenBefore"
               :modelOpenAfter="modelOpenAfter">
        <!-- 自定义组件数据槽扩展，更多数据槽slot见文档 -->
        <template #gridHeader>
            <div class="realtime-header">
                <el-tag :type="signalRConnected ? 'success' : 'danger'" effect="plain">
                    <i :class="signalRConnected ? 'bi bi-wifi' : 'bi bi-wifi-off'"></i>
                    {{ signalRConnected ? '实时连接已建立' : '实时连接已断开' }}
                </el-tag>
                <el-tag type="info" effect="plain" style="margin-left: 10px;">
                    <i class="bi bi-clock-history"></i>
                    最后更新: {{ lastUpdateTime }}
                </el-tag>
            </div>
        </template>
    </view-grid>
</template>
<script setup lang="jsx">
    import extend from "@/extension/wms/realt/realtimeinventory.jsx";
    import viewOptions from './realtimeinventory/options.js'
    import { ref, reactive, getCurrentInstance, watch, onMounted, onBeforeUnmount, computed } from "vue";
    import * as signalR from "@microsoft/signalr";
    import { ElNotification } from 'element-plus';
    
    const grid = ref(null);
    const { proxy } = getCurrentInstance()
    //http请求，proxy.http.post/get
    const { table, editFormFields, editFormOptions, searchFormFields, searchFormOptions, columns, detail, details } = reactive(viewOptions())
    
    // SignalR相关状态
    const signalRConnection = ref(null);
    const signalRConnected = ref(false);
    const lastUpdateTime = ref('暂无数据');
    
    // 使用原始列配置
    const enhancedColumns = computed(() => {
        return columns;
    });

    let gridRef;//对应[表.jsx]文件中this.使用方式一样
    
    // 初始化SignalR连接
    const initSignalR = async () => {
        try {
            const baseUrl = proxy.$baseUrl || 'http://localhost:9991';
            const hubUrl = `${baseUrl}/api/signalr/InventoryHub`;
            
            signalRConnection.value = new signalR.HubConnectionBuilder()
                .withUrl(hubUrl)
                .withAutomaticReconnect()
                .configureLogging(signalR.LogLevel.Information)
                .build();
            
            // 监听连接状态
            signalRConnection.value.onreconnecting(() => {
                signalRConnected.value = false;
                console.log('SignalR正在重新连接...');
            });
            
            signalRConnection.value.onreconnected(() => {
                signalRConnected.value = true;
                console.log('SignalR重新连接成功');
                ElNotification.success({
                    title: '实时连接',
                    message: '实时库存连接已恢复',
                    duration: 2000
                });
            });
            
            signalRConnection.value.onclose(() => {
                signalRConnected.value = false;
                console.log('SignalR连接已关闭');
            });
            
            // 监听库存新增事件
            signalRConnection.value.on('InventoryAdded', (inventoryData) => {
                console.log('收到实时库存数据:', inventoryData);
                lastUpdateTime.value = new Date().toLocaleTimeString();
                
                // 刷新表格数据
                if (gridRef) {
                    gridRef.search();
                }
                
                // 显示通知
                ElNotification.success({
                    title: '实时库存更新',
                    message: `新增库存: ${inventoryData.ProductName}`,
                    duration: 3000
                });
            });
            
            // 启动连接
            await signalRConnection.value.start();
            signalRConnected.value = true;
            console.log('SignalR连接成功');
            
            ElNotification.success({
                title: '实时连接',
                message: '实时库存连接已建立',
                duration: 2000
            });
        } catch (error) {
            console.error('SignalR连接失败:', error);
            signalRConnected.value = false;
            
            ElNotification.error({
                title: '连接失败',
                message: '无法建立实时连接，数据可能不会实时更新',
                duration: 5000
            });
        }
    };
    
    //生成对象属性初始化
    const onInit = async ($vm) => {
        gridRef = $vm;
        //与jsx中的this.xx使用一样，只需将this.xx改为gridRef.xx
        //更多属性见：https://v3.volcore.xyz/docs/view-grid
        
        // 初始化SignalR
        await initSignalR();
    }
    //生成对象属性初始化后,操作明细表配置用到
    const onInited = async () => {
    }
    const searchBefore = async (param) => {
        //界面查询前,可以给param.wheres添加查询参数
        //返回false，则不会执行查询
        return true;
    }
    const searchAfter = async (rows, result) => {
        return true;
    }
    const addBefore = async (formData) => {
        //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
        return true;
    }
    const updateBefore = async (formData) => {
        //编辑保存前formData为对象，包括明细表、删除行的Id
        return true;
    }
    const rowClick = ({ row, column, event }) => {
        //查询界面点击行事件
        // grid.value.toggleRowSelection(row); //单击行时选中当前行;
    }
    const modelOpenBefore = async (row) => {//弹出框打开后方法
        return true;//返回false，不会打开弹出框
    }
    const modelOpenAfter = (row) => {
        //弹出框打开后方法,设置表单默认值,按钮操作等
    }
    //监听表单输入，做实时计算
    //watch(() => editFormFields.字段,(newValue, oldValue) => {	})
    
    // 组件卸载时断开SignalR连接
    onBeforeUnmount(() => {
        if (signalRConnection.value) {
            signalRConnection.value.stop().then(() => {
                console.log('SignalR连接已断开');
            });
        }
    });
    
    //对外暴露数据
    defineExpose({})
</script>
<style lang="less" scoped>
.realtime-header {
    padding: 10px;
    background: #f5f7fa;
    border-radius: 4px;
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    
    .el-tag {
        i {
            margin-right: 5px;
        }
    }
}
</style>
